export const getDatabases = async (data: DataSourceInfo) => {
  const res = await fetch("/api/gen/database", {
    method: "POST",
    body: JSON.stringify(data),
    headers: {
      "Content-Type": "application/json",
    },
  });
  const json = await res.json();
  if (json.code !== 1) {
    window.$message?.error(json.msg);
    throw new Error(json.msg);
  }
  return json;
};

export const getTables = async (data: DataSourceInfo, database: string) => {
  const res = await fetch("/api/gen/table?" + paramsToQueryStr({ database }), {
    method: "POST",
    body: JSON.stringify(data),
    headers: {
      "Content-Type": "application/json",
    },
  });
  const json = await res.json();
  if (json.code !== 1) {
    window.$message?.error(json.msg);
    throw new Error(json.msg);
  }
  return json;
};

export const generateCode = async (
  data: DataSourceInfo,
  database: string,
  params: object
) => {
  const res = await fetch(
    "/api/gen/generateCode?" + paramsToQueryStr({ database, ...params }),
    {
      method: "POST",
      body: JSON.stringify(data),
      headers: {
        "Content-Type": "application/json",
      },
    }
  );
  if (!res.ok) {
    const json = await res.json();
    window.$message?.error(json.msg);
    throw new Error(json.msg || "生成代码失败");
  }
  const blob = await res.blob();

  // 创建一个隐藏的 <a> 标签用于下载
  const link = document.createElement("a");
  link.href = URL.createObjectURL(blob);
  link.setAttribute("download", "generate-code.zip"); // 设置下载文件名
  link.style.display = "none";
  document.body.appendChild(link);

  // 触发点击事件
  link.click();

  // 清理工作
  document.body.removeChild(link);
  URL.revokeObjectURL(link.href);
};

const paramsToQueryStr = (params: Record<string, any>) => {
  return Object.keys(params)
    .map((key) => {
      if (Array.isArray(params[key])) {
        return params[key]
          .map((val: any) => `${key}=${encodeURIComponent(val)}`)
          .join("&");
      } else {
        return `${key}=${encodeURIComponent(params[key])}`;
      }
    })
    .join("&");
};
